using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure;

namespace S.M.SmartMedical.API.Read.Application.Handler
{
    /// <summary>
    /// 获取轮播图详情查询处理器
    /// </summary>
    public class GetCarouselDetailHandler : IRequestHandler<GetCarouselDetailQuery, APIResult<CarouselDto>>
    {
        private readonly MyDbContext _context;
        private readonly IMapper _mapper;
        private readonly ILogger<GetCarouselDetailHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetCarouselDetailHandler(
            MyDbContext context,
            IMapper mapper,
            ILogger<GetCarouselDetailHandler> logger)
        {
            _context = context;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取轮播图详情查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>轮播图详情结果</returns>
        public async Task<APIResult<CarouselDto>> Handle(GetCarouselDetailQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理获取轮播图详情查询，ID：{Id}", request.Id);

                // 查询轮播图
                var carousel = await _context.Carousels
                    .FirstOrDefaultAsync(c => c.Id == request.Id && !c.IsDeleted, cancellationToken);

                if (carousel == null)
                {
                    _logger.LogWarning("轮播图不存在或已删除，ID：{Id}", request.Id);
                    return new APIResult<CarouselDto>
                    {
                        Code = APIEnum.Fail,
                        Message = "轮播图不存在或已删除",
                        Data = null!
                    };
                }

                // 映射为DTO
                var carouselDto = _mapper.Map<CarouselDto>(carousel);

                _logger.LogInformation("获取轮播图详情查询处理完成，ID：{Id}", request.Id);

                return new APIResult<CarouselDto>
                {
                    Code = APIEnum.OK,
                    Message = "获取轮播图详情成功",
                    Data = carouselDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取轮播图详情查询处理异常，ID：{Id}", request.Id);
                return new APIResult<CarouselDto>
                {
                    Code = APIEnum.Fail,
                    Message = "获取轮播图详情失败，系统异常",
                    Data = null!
                };
            }
        }
    }
}